const path = require("path");
const fs = require("fs");
const { translateTexts } = require("./translate");
module.exports = async (message, i18nPath, toLang, baiduAppid, baiduKey) => {
  const i18nFile = path.join(i18nPath, `${toLang}.json`);
  const _message = {};
  for (const key in message) {
    if (Object.hasOwnProperty.call(message, key)) {
      if (/[\u4e00-\u9fa5]+/gim.test(message[key])) {
        _message[key] = message[key];
      }
    }
  }
  const keys = Object.keys(_message);
  const values = Object.values(_message);
  const translateMessage = {};
  try {
    const data = await translateTexts(values, baiduAppid, baiduKey, toLang);
    data.forEach((item, index) => {
      translateMessage[keys[index]] = item;
    });

    fs.writeFileSync(
      i18nFile,
      `${JSON.stringify(
        {
          ...message,
          ...translateMessage,
        },
        null,
        "\t"
      )}`,
      "utf8"
    );
  } catch (error) {}
};
